import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entity';
import { ICreatuser, ILogin } from './interface'

@Injectable()
export class UserService {
	constructor(
		@InjectRepository(User)
		private readonly usersRepository: Repository<User>
	) { }

	/**
	 * 新增用户
	 * @param body
	 */
	async add(body: ICreatuser) {
		const userinfo = await this.usersRepository.findOne({
			user_code: body.user_code
		})
		if (userinfo) {
			return {
				code: -1,
				msg: '账号已经存在'
			}
		}
		return this.usersRepository.save(body).then((res) => {
			return {
				code: 1,
				msg: 'success',
				data: res
			}
		})
	}

	async login(body: ILogin) {
		const userinfo = await this.usersRepository.findOne({
			user_code: body.user_code
		})
		if (!userinfo) {
			return {
				code: -1,
				msg: '账号不存在'
			}
		}
		if (userinfo.password === body.password) {
			return {
				code: 1,
				msg: '登录成功',
				data: {
					user_code: userinfo.user_code,
					user_name: userinfo.user_name,
					avatar: userinfo.avatar,
					role: userinfo.role
				}
			}
		} else {
			return {
				code: 0,
				msg: '账号或密码错误'
			}
		}
	}


}
